/**
 * 购物车工具类
 */

 import StorageUtil from './storage.js'

const storage = new StorageUtil()

class ShopCartUtil{
    constructor(store){
        this.$store = store
        try{
            let json = storage.getItem('shopcart')
            if(json=='null')json = {}
            this.$shopcart = JSON.parse(json)
            
        }catch{
            this.$shopcart = {}
        }
        this.update()
    }

    //更新storage中的内容
    update(){
        const json = JSON.stringify(this.$shopcart)
        // this.$shopcart = JSON.parse(json)
        storage.setItem('shopcart',json)
        this.$store.dispatch('setCommodityCount',this.getLength())
    }

    //增加一件物品,value是物品对象
    add(value){
        const key = value.id
        if(!key)return
        if(this.$shopcart[key]) this.$shopcart[key].length++
        else{
            //商品信息对象
            const comInfo = {}
            //需要的普通信息
            const needInfo = ['money','title','id']
            needInfo.forEach(v=>{
                comInfo[v] = value[v]
            })
            comInfo.img = value.banner[0] ? value.banner[0] : ''
            comInfo.link = '/detail/'+value.id
            comInfo.length = 1
            this.$shopcart[key] = comInfo
        }
        this.update()
    }

    minus(value){
        const key = value.id
        if(!key) return
        const c = this.$shopcart[key]
        if(c){
            c.length--
            if(c.length<=0) this.remove(key)
            this.update()
        }
    }

    remove(key){ 
        const c = this.$shopcart[key]
        if(c){
            delete this.$shopcart[key]
            this.update()
        }
        
    }

    removeAll(){
        this.$shopcart = {}
        this.update()
    }

    get(key){
       return this.$shopcart[key]
    }

    getAll(){
        return this.$shopcart
    }

    setLength(key,len){
        const c = this.$shopcart[key]
        if(c){
            c.length = len
            this.update()
        }
    }

    getLength(){
        let sum = 0
        for(let c in this.$shopcart){
            sum+=this.$shopcart[c].length
        }
        return sum
    }

}

export default ShopCartUtil